﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using COFE.Core.Validater;

namespace COFE.Core.Filter
{
    public class PropertyEntryFilter : EntryFilterBase
    {
        #region Constructor

        public PropertyEntryFilter(object property, string value, string id = "")
            : base(value, id)
        {
            SupportedMatchType = MatchType.MatchThisEntry;
            Property = property;
        }

        #endregion

        #region Methods

        public override string Type { get { return 
            AliasExtension.getAlias(Property).ToLower(); } }

        public override MatchType matches(
            IInternalFileSystemInfoExA entry,
            params IOptionFilter[] options)
        {
            bool match = false;
            
            if (entry.IsPropertySupported(Property))
            {                
                int op = Value.StartsWith(">") ? 1 : 
                    Value.StartsWith("<") ? -1 : 0;
                string value = Value.TrimStart('<', '>');
                var entryValue = entry.GetProperty(Property);

                Func<int, int, bool> sameMagnitude = 
                    (a, b) => (a < 0 && b < 0) || (a > 0 && b > 0);

                if (op == 0)
                {                    
                    match = entryValue.ValueAsString.IndexOf(Value,
                        StringComparison.InvariantCultureIgnoreCase) != -1;
                }
                else
                {
                    try
                    {
                    switch (PropertyTypeExtension
                        .GetDefaultPropertyType(Property).ToString())
                    {                       
                        case "System.Int16":
                        case "System.Int32":
                        case "System.Int64":
                            match = sameMagnitude(op, 
                                entryValue.ValueAsInt64.CompareTo(
                                Int64.Parse(value)));
                            break;
                        case "System.DateTime":
                            match = sameMagnitude(op,
                                entryValue.ValueAsLocalDateTime.CompareTo(
                                DateTime.Parse(Value)));
                            break;
                    }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("PropertyFilter " + ex.Message);
                    }
                }
            }

            return match ? MatchType.MatchThisEntry : MatchType.None;     
        }

        #endregion

        #region Data

        #endregion

        #region Public Properties

        public object Property { get; protected set; }

        #endregion

    }
}
